const fs = require('fs');
const path = require('path');

// 确保上传目录存在
const projectRoot = path.join(__dirname, '..');
const uploadsDir = path.join(projectRoot, 'uploads');
const menuImagesDir = path.join(uploadsDir, 'menu-images');

console.log('检查上传目录是否存在...');

if (!fs.existsSync(uploadsDir)) {
  console.log(`创建上传根目录: ${uploadsDir}`);
  fs.mkdirSync(uploadsDir, { recursive: true });
} else {
  console.log(`上传根目录已存在: ${uploadsDir}`);
}

if (!fs.existsSync(menuImagesDir)) {
  console.log(`创建菜单图片目录: ${menuImagesDir}`);
  fs.mkdirSync(menuImagesDir, { recursive: true });
} else {
  console.log(`菜单图片目录已存在: ${menuImagesDir}`);
}

// 创建后端上传目录的符号链接
const backendUploadsDir = path.join(projectRoot, 'backend', 'uploads');
if (!fs.existsSync(backendUploadsDir)) {
  console.log(`创建后端上传目录符号链接: ${backendUploadsDir} -> ${uploadsDir}`);
  try {
    fs.symlinkSync(uploadsDir, backendUploadsDir, 'dir');
  } catch (err) {
    console.log(`创建符号链接失败，尝试创建实际目录: ${err.message}`);
    if (!fs.existsSync(backendUploadsDir)) {
      fs.mkdirSync(backendUploadsDir, { recursive: true });
    }
    const backendMenuImagesDir = path.join(backendUploadsDir, 'menu-images');
    if (!fs.existsSync(backendMenuImagesDir)) {
      fs.mkdirSync(backendMenuImagesDir, { recursive: true });
    }
  }
} else {
  console.log(`后端上传目录已存在: ${backendUploadsDir}`);
}

console.log('上传目录检查完成!');